package cn.jdemo.socket.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 为每个socket连接创建一个处理线程
 */
public class Demo02 {

    private static ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactory(){
        final AtomicInteger atomicInteger = new AtomicInteger(1);
        final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = defaultFactory.newThread(r);
            thread.setName("custom thread-"+atomicInteger.getAndIncrement());
            return thread;
        }
    });

    public static void main(String[] args) throws IOException {
        ServerSocket sSocket = new ServerSocket(8000);
        while (true){
            // 阻塞1:阻塞，直到建立连接
            Socket accept = sSocket.accept();

            executorService.submit(()->{
                try {
                    handleSocket(accept);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

        }
    }

    public static void handleSocket(Socket clientSocket) throws IOException {
        byte[] bytes = new byte[1024];
        while (true){
            // 阻塞2:阻塞，直到输入数据可用、检测到文件结尾或引发异常
            // (接收客户端的数据，阻塞方法，没有数据可读时就阻塞)
            int read = clientSocket.getInputStream().read(bytes);
            if (read != -1) {
                System.out.println(Thread.currentThread().getName()+"接收到客户端的数据：" + new String(bytes, 0, read));
            }
        }
        //服务器向客户端发送数据
        /*clientSocket.getOutputStream().write("ACK:HelloClient".getBytes());
        clientSocket.getOutputStream().flush();*/
    }
}
